import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '../store'
import { ElMessage } from 'element-plus'


function hasUrl(url: any, next: any) {
  let result = store.getters.getUser.menus_url.some((item: any) => item == url)
  if (result) {
    next()
  } else {
    //没有权限就强制跳转到首页
    ElMessage.error("您没有当前权限，已为您自动跳转")
    next('/home')
  }
}


export const routesIndex = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/role', next)
    }
  },
  {
    path: '/user',
    component: () => import('../views/admin/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter(to: any, from: any, next: any) {
      hasUrl('/user', next)
    }
  }

]

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue'),
        meta: {
          title: '首页'
        }
      },
      ...routesIndex,
      {
        path: '',
        redirect: "/home"
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

//调用全局前置导航守卫
router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    next()
    return
  }
  //如果已经登录 就放行
  if(store.getters.getUser){    
    next()
    return
  }
  //以上条件都不符合 就直接强制跳转到登录
  next('/login')
})

export default router

// interface People {
//   name:string,
//   age:number
// }

// var people:People = {
// name:'777',
// age:999,
// sex:'nv'
// }

